KindEditor.plugin('product', function(K) {
	var self = this, name = 'product',
		productsListJson = K.undef(self.productsListJson, self.basePath + 'php/articles_manager_json.php'),
		fileServerUrl = K.undef(self.fileServerUrl, self.basePath),
		lang = self.lang(name + '.');
	
	self.plugin.productDialog = function(options) {
		var width = K.undef(options.width, 650),
			height = K.undef(options.height, 510),
			clickFn = options.clickFn;
		var html = [
			'<div style="padding:10px 20px;">',
			// header start
			'<div class="ke-plugin-product-header">',
			// left start
			'<div class="ke-left">',
			'搜索关键字: <input type="text" name="keyword" class="ke-keyword" size="20" /><span class="ke-button-common ke-button-outer ke-dialog-no" title="搜索"><input class="ke-button-common ke-button" type="button" id="btnKeSearch" value="搜索"></span>',
			'</div>',
			// right start
			'<div class="ke-right">',
			'</div>',
			'<div class="ke-clearfix"></div>',
			'</div>',
			// body start
			'<div class="ke-plugin-product-body"></div>',
			'<div class="ke-plugin-product-footer"></div></div>'
		].join('');
		var dialog = self.createDialog({
			name : name,
			width : width,
			height : height,
			title : self.lang(name),
			body : html,
			yesBtn : {
				name : "插入产品",
				click : function(e) {
					var rows = $(".ke-cell input[type='radio']:checked").closest("tr");
					rows.each(function(i, item){
						var row = $(item);
						var id = row.find(".ke-id >input").val();
						var name = row.find(".ke-name").text();
						var author = row.find(".ke-author").text();
						var price = row.find(".ke-price").text();
						var iconUrl = row.find(".ke-icon").children("img").attr("src");
						var html = '<div style="width:33%;float:left;"><img src="'+ iconUrl +'" border="0" height="180" align="right"></div><div class="width: 60%;float:left;"><p style="font-size: 18px;line-height: 1.8em;text-indent:10px;">商品名称：'+name+'</p><p style="font-size: 18px;line-height: 1.8em;text-indent:10px;">艺术家：'+author+'</p><p style="font-size: 18px;line-height: 1.8em; text-indent:10px;">价格：'+price+'</p></div><div style="clear:both"></div>';
			        self.insertHtml(html + '<br/>');
					});
					self.hideDialog().focus();
				}
			}

		}),
		div = dialog.div,
		bodyDiv = K('.ke-plugin-product-body', div),
		footDiv = K('.ke-plugin-product-footer', div);
		function reloadPage(func, title, pn) {
			dialog.showLoading(self.lang('ajaxLoading'));

			var pageNo = pn || 1, pageSize = 5;
			var param = 'currentPage=' + pageNo + '&pageSize=' + pageSize+'&name='+(title || "");
			K.ajax(K.addParam(productsListJson, param), function(data) {
				dialog.hideLoading();
				func(data, pageNo, pageSize);
			}, 'GET');
		}
		var elList = [];
		function bindEvent(el, result, data, createFunc) {
			// var fileUrl = K.formatUrl(data.url || (result.current_url + data.filename), 'absolute'),
			// 	dirPath = encodeURIComponent(data.url || (result.current_dir_path + data.filename) + '/');	
			// if (data.is_dir) {
			// 	el.click(function(e) {
			// 		reloadPage(createFunc);
			// 	});
			// } else if (data.is_photo) {
			// 	el.click(function(e) {
			// 		clickFn.call(this, fileUrl, data.filename);
			// 	});
			// } else {
			// 	el.click(function(e) {
			// 		clickFn.call(this, fileUrl, data.filename);
			// 	});
			// }
			// elList.push(el);
		}
		function createCommon(result, createFunc) {
			// remove events
			K.each(elList, function() {
				this.unbind();
			});
			var btnSearch = K('#btnKeSearch', div);
			var keyword = K('.ke-keyword', div);
			btnSearch.click(function(e){
				dialog.hideLoading();
				reloadPage(createList, keyword.val());
			});
			bodyDiv.html('');
		}
		function createList(result, pageNo, pageSize) {
			createCommon(result, createList);
			var table = document.createElement('table');
			table.className = 'ke-table';
			table.cellPadding = 0;
			table.cellSpacing = 0;
			table.border = 0;
			bodyDiv.append(table);

			var row = K(table.insertRow(i));
			K(row[0].insertCell(0)).addClass('ke-cell ke-id').html("ID");
			K(row[0].insertCell(1)).addClass('ke-cell ke-icon').html("产品图");
			K(row[0].insertCell(2)).addClass('ke-cell ke-name').html("产品名称");
			K(row[0].insertCell(3)).addClass('ke-cell ke-author').html("艺术家");
			K(row[0].insertCell(4)).addClass('ke-cell ke-category').html("分类");

			var list = result.artworks;
			for (var i = 0, len = list.length; i < len; i++) {
				var data = list[i];
				row = K(table.insertRow(i+1));
				row.mouseover(function(e) {
					K(this).addClass('ke-on');
				})
				.mouseout(function(e) {
					K(this).removeClass('ke-on');
				});
				row.css('cursor', 'pointer');

				// var checkbox = K('<input type="checkbox" name="id" value="'+ data.id+'"/>');
				// K(row[0].insertCell(0)).addClass('ke-cell ke-id').append(checkbox);
				// bindEvent(cell0, result, data, createList);
				var checkbox = K('<input type="radio" name="id" value="'+ data.id+'"/>');
				K(row[0].insertCell(0)).addClass('ke-cell ke-id').append(checkbox);
				
				var pic = "/cms/images/avatar/leijun.jpg";
				if(data.pictures && data.pictures.length){
					pic = fileServerUrl + data.pictures[0].id + "?w=64&h=64";
				}
				var img = K('<img name="icon" src="'+ pic +'" border="0" width="64" height="64" />');
				K(row[0].insertCell(1)).addClass('ke-cell ke-icon').append(img); 
				var name = K(row[0].insertCell(2)).addClass('ke-cell ke-name').html(data.name);
				name.attr('title', data.name);

				K(row[0].insertCell(3)).addClass('ke-cell ke-author').html(data.artworkAuthor.value);
				K(row[0].insertCell(4)).addClass('ke-cell ke-category').html(data.artworkCategory.parent.value);
				K(row[0].insertCell(5)).addClass('ke-cell ke-hidden ke-price').html('￥'+data.price);
			}
			if(!K('.ke-pager').length){
				var pager = K('<div class="ke-dialog-footer"><ol class="ke-pager"></ol><input type="hidden" value="1" name="pageIndex" id="pageIndex" /></div>');
				footDiv.append(pager);
			}

			var keyword = K('.ke-keyword', div);
			var pageIndex = K('#pageIndex', div);
			var pagination = K('.ke-pager', div);
			var total = result.totalRecords, totalPages = result.totalPages, currentPage = pageNo;

			if(currentPage > 1){
				var prevNode = K('<li><a href="javascript:void(0)" class="ke-prevPage">上一页</a></li>');
				prevNode.click(function(e){
					var pn = pageIndex.val();
					pageIndex.val(--pn);
					reloadPage(createList, keyword.val(), pn);
				});
				if(!K(".ke-prevPage").length){
					pagination.append(prevNode);
				}
			}else{
				$(".ke-prevPage").closest("li").remove();
			}

			if(totalPages > 1 && currentPage < totalPages){
				var nextNode = K('<li><a href="javascript:void(0)" class="ke-nextPage">下一页</a></li>');
				nextNode.click(function(e){
					var pn = pageIndex.val();
					pageIndex.val(++pn);
					reloadPage(createList, keyword.val(), pn);
				});
				if(!K(".ke-nextPage").length){
					pagination.append(nextNode);
				}
			}else{
				$(".ke-nextPage").closest("li").remove();
			}
		}

		reloadPage(createList);
		return dialog;
	};

	self.clickToolbar(name, function() {
		self.plugin.productDialog({
			clickFn : function () {
				//self.exec('inserthtml', '');
				// Bugfix: [Firefox] 上传图片后，总是出现正在加载的样式，需要延迟执行hideDialog
				setTimeout(function() {
					self.hideDialog().focus();
				}, 0);
			}
		});
	});

});
